package com.xianggu.springBoot;


import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;

import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.util.Map;

/**
 * @author chengjy
 * @date 2025/3/5
 */
public class XiangguApplication {
    private static final int PORT = 8080;
    private static final String CONTEXT_PATH = "/myapp";

    public static void run(Class<?> configClass, String ... args){
        // 创建Spring应用上下文
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(configClass);
        context.refresh();

        // 启动tomcat
        WebServer webServer = getWebServer(context);
        webServer.start(context);
//        startTomcat(context);
    }

    public static WebServer getWebServer(ApplicationContext applicationContext) {
        Map<String, WebServer> webServers = applicationContext.getBeansOfType(WebServer.class);

        if(webServers.isEmpty()){
            throw new RuntimeException("没有找到WebServer的实现类");
        }
        if(webServers.size() > 1){
            throw new RuntimeException("WebServer的实现类只能有一个");
        }

        return webServers.values().stream().findFirst().get();
    }

    private static void startTomcat(AnnotationConfigWebApplicationContext applicationContext) {

    }


    // 示例Servlet
//    static class HelloServlet extends HttpServlet {
//        @Override
//        protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
//            try {
//                resp.getWriter().print("Hello from Embedded Tomcat!");
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }
}
